import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '../stores/user'
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import StudentLayout from '../layouts/StudentLayout.vue'
import TeacherLayout from '../layouts/TeacherLayout.vue'

const router = createRouter({
  history: createWebHistory('/'),
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'login',
      component: Login,
      meta: { requiresAuth: false }
    },
    {
      path: '/register',
      name: 'register',
      component: Register,
      meta: { requiresAuth: false }
    },
    {
      path: '/student',
      component: StudentLayout,
      meta: { requiresAuth: true, role: 'student' },
      children: [
        {
          path: '',
          redirect: '/student/profile'
        },
        {
          path: 'profile',
          name: 'student-profile',
          component: () => import('../views/student/Profile.vue')
        },
        {
          path: 'test',
          name: 'student-test',
          component: () => import('../views/student/Test.vue')
        }
      ]
    },
    {
      path: '/teacher',
      component: TeacherLayout,
      meta: { requiresAuth: true, role: 'teacher' },
      children: [
        {
          path: '',
          redirect: '/teacher/profile'
        },
        {
          path: 'profile',
          name: 'teacher-profile',
          component: () => import('../views/teacher/Profile.vue')
        },
        {
          path: 'user-management',
          name: 'user-management',
          component: () => import('../views/teacher/UserManagement.vue')
        },
        {
          path: 'student-results',
          name: 'student-results',
          component: () => import('../views/teacher/StudentResults.vue')
        },
        {
          path: 'question-management',
          name: 'question-management',
          component: () => import('../views/teacher/QuestionManagement.vue'),
          meta: { requiresSchoolAdmin: true }
        },
        {
          path: 'teacher-approval',
          name: 'teacher-approval',
          component: () => import('../views/teacher/TeacherApproval.vue'),
          meta: { requiresAdmin: true }
        }
      ]
    },
    {
      path: '/:pathMatch(.*)*',
      redirect: '/login'
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  const isAuthenticated = userStore.isAuthenticated
  const userRole = userStore.userRole

  // 检查用户是否是校级管理员
  const isSchoolAdmin = () => {
    if (userRole === 'super_admin') return true;
    
    if (!userStore.userInfo?.extraInfo) return false;
    
    try {
      const extraInfo = JSON.parse(userStore.userInfo.extraInfo);
      return extraInfo.admin_role === 'SCHOOL_ADMIN';
    } catch (e) {
      console.error('解析管理员角色失败:', e);
      return false;
    }
  };

  // 检查用户是否是管理员（系级以上）
  const isAdmin = () => {
    if (userRole === 'super_admin') return true;
    
    if (!userStore.userInfo?.extraInfo) return false;
    
    try {
      const extraInfo = JSON.parse(userStore.userInfo.extraInfo);
      const adminRole = extraInfo.admin_role;
      return ['SCHOOL_ADMIN', 'DEPARTMENT_ADMIN', 'MAJOR_ADMIN'].includes(adminRole);
    } catch (e) {
      console.error('解析管理员角色失败:', e);
      return false;
    }
  };

  // 不需要登录的路由
  const publicRoutes = ['/login', '/register']
  
  if (!isAuthenticated && !publicRoutes.includes(to.path)) {
    next('/login')
  } else if (isAuthenticated && publicRoutes.includes(to.path)) {
    // 已登录用户访问登录/注册页面，重定向到对应的首页
    if (userRole === 'teacher' || userRole === 'super_admin') {
      next('/teacher/profile')
    } else {
      next('/student/profile')
    }
  } else if (isAuthenticated) {
    // 检查用户角色权限
    if (to.path.startsWith('/teacher') && userRole !== 'teacher' && userRole !== 'super_admin') {
      next('/student/profile')
    } else if (to.path.startsWith('/student') && userRole !== 'student') {
      next('/teacher/profile')
    } else if (to.meta.requiresSchoolAdmin && !isSchoolAdmin()) {
      // 校级管理员权限检查
      next('/teacher/profile')
    } else if (to.meta.requiresAdmin && !isAdmin()) {
      // 管理员权限检查（系级以上）
      next('/teacher/profile')
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router 